const db = require('../db/index.js')
const { getHomeworkListUtil } = require('./homework')

function addStudent(ctx) {
  return new Promise(resolve => {
    let msg = ''
    const { name } = ctx.request.body
    if (name) {
      db.student.find({ name }, function(err, docs) {
        if (!err && docs.length === 0) {
          db.student.insert({
            ...ctx.request.body,
            created: Date.now()
          })
          ctx.response.status = 200
          msg = '添加成功'
        } else {
          ctx.response.status = 400
          msg = err || '已经存在'
        }
        ctx.response.body = {
          msg
        }
        resolve()
      })
    } else {
      // TODO 后续处理重复问题
      db.student.insert(ctx.request.body.map(student => {
        return {
          ...student,
          created: Date.now()
        }
      }))
      ctx.response.status = 200
      msg = '添加成功'
      ctx.response.body = {
        msg
      }
      resolve()
    }
  })
}

function getStudentListUtil(ctx) {
  return new Promise(resolve => {
    db.student.find({}, function(err, data) {
      if (err) {
        ctx.response.status = 400
        ctx.response.body = err
        return
      }
      resolve(data)
    })
  })
}

async function getStudentList(ctx) {
  const data = await getStudentListUtil(ctx)
  const homework = await getHomeworkListUtil({
    $or: data.map(item => {
      return {
        student: item._id
      }
    })
  })
  ctx.response.status = 200
  ctx.response.body = data.map(item => {
    return {
      ...item,
      homework: homework.filter(homework => homework.student === item._id)
    }
  })
}

module.exports = {
  addStudent,
  getStudentList
}
